<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入单号/姓名"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="incomeList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
          width="60px;"
        ></el-table-column>
        <el-table-column
          v-for="item in tableColumns"
          :key="item.key"
          align="center"
          :label="item.title"
          :prop="item.key"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getIncomeList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="60%"
      custom-class="dialog"
    >
      <el-form
        :model="incomeForm"
        :rules="incomeFormRules"
        ref="incomeFormRef"
        label-width="80px"
        label-position="right"
        style="padding: 0 20px"
        size="small"
      >
        <el-form-item label="单号" prop="order_no" v-if="dialogType === 'edit'">
          <el-input
            type="text"
            v-model="incomeForm.order_no"
            placeholder="单号"
            maxlength="24"
            disabled
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开单时间" prop="order_time">
              <el-date-picker
                v-model="incomeForm.order_time"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择开单时间"
                clearable
                :disabled="incomeForm.verify === 1"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="employee">
              <el-select
                v-model="incomeForm.employee"
                placeholder="选择员工"
                clearable
                @change="selectChange"
                :disabled="incomeForm.verify === 1"
              >
                <el-option
                  v-for="item in employees"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会计科目" prop="acc_title">
              <el-cascader
                v-model="selectedKeys"
                :options="accountList"
                :props="props"
                @change="handleChange"
                clearable
                :disabled="incomeForm.verify === 1"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账号" prop="account">
              <el-select
                v-model="incomeForm.account"
                placeholder="收款账号"
                clearable
                :disabled="incomeForm.verify === 1"
              >
                <el-option
                  v-for="item in accounts"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="金额" prop="money">
              <el-input
                v-model="incomeForm.money"
                placeholder="金额"
                clearable
                :disabled="incomeForm.verify === 1"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收入来源">
              <el-input
                v-model="incomeForm.source"
                placeholder="收入来源"
                clearable
                :disabled="incomeForm.verify === 1"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="incomeForm.desc"
            placeholder="备注"
            clearable
            :disabled="incomeForm.verify === 1"
          />
        </el-form-item>
        <el-form-item label="审核" prop="verify" v-if="incomeForm.verify === 1">
          <el-switch
            v-model="incomeForm.verify"
            :active-value="1"
            :inactive-value="0"
            active-text="通过"
            :disabled="incomeForm.verify === 1"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <el-tabs
        v-model="activeName"
        style="padding: 0: 20px"
        v-if="dialogType == 'new'"
      >
        <el-tab-pane label="用户资金借出情况" name="lend">
          <el-table
            :data="lends"
            border
            size="small"
            show-summary
            :summary-method="getSummaries"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column
              align="center"
              label="时间"
              prop="order_time"
            ></el-table-column>
            <el-table-column
              align="center"
              label="姓名"
              prop="employee_name"
            ></el-table-column>
            <el-table-column
              align="center"
              label="金额(元)"
              prop="money"
            ></el-table-column>
            <el-table-column
              align="center"
              label="已还款额(元)"
              prop="repayment"
            ></el-table-column>
            <el-table-column align="center" label="余额(元)" prop="balance">
              <template slot-scope="scope">
                <span style="color: red; font-weight: bold">{{
                  scope.row.balance.toFixed(2)
                }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column
              align="center"
              label="还款额(元)"
              prop="repay_money"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.repay_money"
                  placeholder="还款额"
                  size="small"
                ></el-input>
              </template>
            </el-table-column> -->
            <el-table-column
              align="center"
              label="备注"
              prop="desc"
            ></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="账户资金情况" name="bank">
          <el-table :data="vAccounts" size="mini" border>
            <el-table-column
              label="序号"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="账户"
              prop="name"
              align="center"
            ></el-table-column>
            <el-table-column
              label="金额(元)"
              prop="balance"
              align="center"
            ></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button type="default" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="HandleSave(false)" :disabled="incomeForm.verify === 1">保存</el-button>
        <el-button
          type="success"
          size="medium"
          @click="HandleSave(true)"
          :disabled="incomeForm.verify === 1"
          >保存并审核</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDate } from "@/utils/datetime";
import {
  getFundBills,
  addFundBill,
  updateFundBill,
  delFundBill,
  getUserFundBills,
  addRepaymentBill,
} from "@/api/fundbill";

import { getEmployeeList, getAccountTitles } from "@/api/base";
import { getAccountList } from "@/api/finance";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  order_no: "",
  order_time: getCurrentDate(),
  employee: undefined,
  acc_title: undefined,
  account: null,
  money: 0,
  category: 1,
  desc: "",
  source: "",
  user: undefined,
  verify: 0,
};

const defaultRepayForm = {
  id: undefined,
  bill: null,
  bill_date: getCurrentDate(),
  money: 0,
  user: undefined,
};

export default {
  name: "Income",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    return {
      incomeForm: Object.assign({}, defaultForm),
      incomeFormRules: {
        employee: [{ required: true, message: "请选择员工", trigger: "blur" }],
        order_time: [
          { required: true, message: "请输入开单时间", trigger: "blur" },
        ],
        acc_title: [
          { required: true, message: "请选择会计科目", trigger: "blur" },
        ],
        account: [
          { required: true, message: "请选择收款账号", trigger: "blur" },
        ],
        money: [{ validator: checkMoney, trigger: "blur" }],
      },

      title: "其他收入",
      employees: [],
      accountList: [],
      accounts: [],
      vAccounts: [],
      lends: [],
      selections: [],
      selectedKeys: [],
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      dialogVisible: false,
      dialogType: "new",
      activeName: "lend",
      incomeList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
        category: 1,
        search_date: "",
      },

      tableColumns: [
        {
          key: "order_no",
          title: "单号",
        },
        {
          key: "order_time",
          title: "时间",
        },
        {
          key: "employee_name",
          title: "姓名",
        },
        {
          key: "title_name",
          title: "科目",
        },
        {
          key: "account_name",
          title: "收款账号",
        },
        {
          key: "money",
          title: "金额",
          filter: true,
        },
        {
          key: "verify_name",
          title: "审核",
          filter: true,
        },
        {
          key: "desc",
          title: "备注",
        },
        {
          key: "source",
          title: "收入来源",
        },
      ],

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getIncomeList();
    this.getAccountTitles();
    this.getEmployeeList();
    this.getAccountCodeList(); //账号
  },
  methods: {
    getIncomeList() {
      this.listLoading = true;
      getFundBills(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.incomeList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },

    getAccountCodeList() {
      getAccountList().then((res) => {
        this.accounts = res;
        this.vAccounts = res;
      });
    },

    getAccountTitles() {
      getAccountTitles({}).then((res) => {
        this.accountList = res;
      });
    },

    getEmployeeList() {
      getEmployeeList().then((res) => {
        this.employees = res;
      });
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "money" ||
          column.property === "repayment" ||
          column.property === "balance"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "money") {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getIncomeList();
    },
    getUserBills(employee) {
      const params = {
        category: 3,
        employee: employee,
      };
      getUserFundBills(params)
        .then((res) => {
          this.lends = res.map((item) => {
            item["repay_money"] = 0;
            return item;
          });
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取用户资金借出数据失败");
        });
    },
    // 增加
    handleAdd() {
      this.incomeForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.lends = [];
      this.getAccountCodeList();
      this.$nextTick(() => {
        this.$refs.incomeFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.incomeForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(
          this.incomeForm.acc_title,
          this.accountList
        );
        this.$refs.incomeFormRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delFundBill(row.id);

          this.incomeList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave(flag) {
      this.$refs.incomeFormRef.validate(async (valid) => {
        if (!valid) return;

        if (flag) {
          this.incomeForm.verify = 1;
        }

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.incomeForm.user) {
            this.incomeForm.user = this.uid;
          }
          res = await updateFundBill(this.incomeForm);
          console.log(isEdit, res);
          const index = this.incomeList.findIndex((v) => v.id === res.id);
          this.incomeList.splice(index, 1, res);
        } else {
          try {
            this.incomeForm.user = this.uid;
            res = await addFundBill(this.incomeForm);
          } catch (err) {
            console.log(err);
            this.$message.error("其他收入单保存失败!");
            return;
          }
          // try {
          //   const repayments = this.selections.map((item) => {
          //     let repayment = Object.assign({}, defaultRepayForm);
          //     repayment.bill = item.id;
          //     repayment.money = item.repay_money;
          //     repayment.user = this.uid;
          //     return repayment;
          //   });
          //   if (repayments.length > 0) {
          //     const res_bill = await addRepaymentBill(repayments);
          //     console.log(res_bill);
          //   }
          // } catch (err) {
          //   console.log(err);
          //   this.$message.error("还款保存失败!");
          //   return;
          // }

          this.getIncomeList();
        }

        const { order_no, employee_name, money } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>单号: ${order_no}</div>
              <div>姓名: ${employee_name}</div>
              <div>金额: ${money}</div>
            `,
          type: "success",
        });
      });
    },
    selectChange(value) {
      this.getUserBills(value);
    },
    handleChange(value) {
      if (this.selectedKeys.length > 0) {
        this.incomeForm.acc_title =
          this.selectedKeys[this.selectedKeys.length - 1];
      } else {
        this.incomeForm.acc_title = undefined;
      }
    },
    handleSelectionChange(val) {
      this.selections = val;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }

  .item {
    margin-top: 8px;
  }
}
</style>